package com.banyuan.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet("/last2")
public class LastTimeServlet2 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cookie lastCookie = getCookie(req, "last");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;utf-8");
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String nowTime = sdf.format(date);
        String encode = URLEncoder.encode(nowTime, "UTF-8");
        if (lastCookie == null) {
            Cookie cookie = new Cookie("last",encode);
            resp.addCookie(cookie);
            resp.getWriter().write("这是你首次访问");
        } else {
            String value = lastCookie.getValue();
            String decode = URLDecoder.decode(value, "UTF-8");
            resp.getWriter().write("欢迎回来，你上次访问时间是:" + decode);
            lastCookie.setValue(encode);
            resp.addCookie(lastCookie);

        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }


    public Cookie getCookie(HttpServletRequest req, String name) {
        Cookie[] cookies = req.getCookies();
        if (cookies == null || cookies.length < 1) {
            return null;
        }
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(name)) {
                return cookie;
            }
        }
        return null;
    }
}
